import serial
import time
import sys
import os

# Function to read from Pico2
def read_pico2_serial(port='/dev/ttyACM0', baudrate=115200):
    print(f"Attempting to connect to {port}, baudrate: {baudrate}")
    
    try:
        # Open serial port
        ser = serial.Serial(port, baudrate, timeout=1)
        print(f"Serial connection successful to {port}. Reading data...")
        
        # Continuously read data
        while True:
            if ser.in_waiting > 0:
                line = ser.readline().decode('utf-8').rstrip()
                print(f"Pico2: {line}")
            time.sleep(0.1)  # Short sleep to reduce CPU usage
            
    except serial.SerialException as e:
        print(f"Serial error: {e}")
    except KeyboardInterrupt:
        print("Program exited")
    finally:
        if 'ser' in locals() and ser.is_open:
            ser.close()
            print("Serial port closed")

if __name__ == "__main__":
    # Use fixed port
    port = '/dev/ttyACM0'
    
    # Override with command line argument if provided
    if len(sys.argv) > 1:
        port = sys.argv[1]
    
    # Verify port exists
    if os.path.exists(port):
        read_pico2_serial(port)
    else:
        print(f"Error: Port {port} does not exist.")
        print("Please check your connection or specify a valid port.")
        print("Example usage: python read_pico2.py /dev/ttyACM0")